<template>
    <div class="container">
        <a-form :model="search" autocomplete="off" @keyup.enter="handleSearch()">
            <iSearch>
                <template #FormData>
                    <a-form-item>
                        <iInput v-model:value="search.original_name" tip="附件名称" placeholder="请输入附件名称"></iInput>
                    </a-form-item>
                </template>
                <template #Button>
                    <a-button type="primary" @click="handleSearch">查询</a-button>
                    <a-button @click="handleReset">重置</a-button>
                    <iUpload :category="active" :auth="['general:attachment:upload','disabled']" @change="handleSearch"></iUpload>
                    <a-button @click="handleBatchClassify" :disabled="!hasSelected">归类</a-button>
                </template>
            </iSearch>
        </a-form>
        <a-tabs v-model:activeKey="active" style="margin-top: 10px;" @change="handleSearch">
            <a-tab-pane v-for="item in TabsData" :key="item.value" :tab="item.title">
                <iTable :row-selection="{ selectedRowKeys: state.selectedRowKeys, onChange: onSelectChange }" rowKey="id" @search="handlePagination" :total="total" :columns="columns" :tableData="tableData" :loading="loading" style="margin-top: 0px;">
                    <template #file_url="{ record }">
                        <a-flex gap="middle" align="center">
                            <template v-if="['image/png','image/webp','image/jpeg'].includes(record.file_type)">
                                <a-image :width="100" :height="100" :fallback="LoadStaticPath('/storage/static/common/image_error.png')" :src="LoadStaticPath(record.file_url)" style="object-fit: scale-down;" />
                            </template>
                            <template v-else>
                                <div style="width: 100px;height: 100px;font-size: 25px;display: flex;justify-content: center;align-items: center;">
                                    <FileTextOutlined />
                                </div>
                            </template>
                            <a :href="LoadStaticPath(record.file_url)" target="_blank">下载</a>
                        </a-flex>
                    </template>

                    <template #category="{ record }">
                        <span v-if="TabsData.find((item: any) => item.value == record.category)?.title"> {{ TabsData.find((item: any) => item.value == record.category)?.title }} </span>
                        <span v-else>
                            <a href="javascript:void(0)" style="color: red;" @click="handleClassify(record)">立即分配</a>
                        </span>
                    </template>
                    <template #file_size="{ record }">
                        {{ FileSize(record.file_size) }} / {{ record.file_type }}
                    </template>
                    <template #operate="{ record }">
                        <a-flex gap="small">
                            <a-button type="link" v-if="isPick">选择</a-button>
                            <iDelete :auth="['general:attachment:del','disabled']" @delete="handleDelete(record.id)"></iDelete>
                        </a-flex>
                    </template>
                </iTable>
            </a-tab-pane>
        </a-tabs>


        <a-modal v-model:open="classify_visible" wrap-class-name="full-modal" title="归类" @cancel="handleCancelClassify" @ok="handleOkClassify">
            <div class="formdata-content">
                <a-form ref="FormData" :model="FormData" autocomplete="off">
                    <a-select v-model:value="FormData.category" placeholder="请选择一个类别" style="width: 100%">
                        <a-select-option v-for="(item,index) in store.Config.attachment_category" :key="index" :value="item.value">{{ item.title }}</a-select-option>
                    </a-select>
                </a-form>
            </div>
        </a-modal>

    </div>
</template>

<script setup lang="ts">
import { iPb } from '@/protobuf/interface';
import { ListAttachment, UpdateAttachment, DeleteAttachment } from '@/api/attachment';
import { computed, reactive, ref } from 'vue';

import { onMounted } from 'vue';
import { FormInstance, TableColumnsType } from 'ant-design-vue';
import { Message } from '@/tool/antdv';
import { LoadStaticPath } from '@/tool/common';
import { FileSize } from '@/tool/files';
import { useStore } from '@/stores/index'

defineProps<{
    isPick: boolean
}>()

const store = useStore()
const TabsData = ref<any>()
const tableData = ref<Array<iPb.IDbAttachment>>([])
const total = ref<number>(0)

const active = ref<string>("")
const search = ref<iPb.Admin.IListAttachmentRequest>(iPb.Admin.ListAttachmentRequest.create())

const loading = ref<Boolean>(false)
const EditLoading = ref<Boolean>(false)

const handleReset = () => {
    search.value = iPb.Admin.ListAttachmentRequest.create()
    initList()
}

const handleSearch = () => {
    initList()
}

type Key = string | number;
const state = reactive<{
    selectedRowKeys: Key[];
}>({
    selectedRowKeys: [],
});

const FormDataRef = ref<FormInstance>()
const FormData = ref<iPb.Admin.IUpdateAttachmentRequest>(iPb.Admin.UpdateAttachmentRequest.create())

const onSelectChange = (selectedRowKeys: number[]) => {
    state.selectedRowKeys = selectedRowKeys;
}

const hasSelected = computed(() => {
    return state.selectedRowKeys && state.selectedRowKeys.length > 0
});

const classify_visible = ref<boolean>(false)

const attachmentIds = ref<number[]>([])

const handleBatchClassify = () => {
    if (!state.selectedRowKeys || state.selectedRowKeys.length == 0) {
        return
    }
    FormDataRef.value?.resetFields()
    attachmentIds.value = state.selectedRowKeys as number[]
    classify_visible.value = true
}

const handleClassify = (record: iPb.IDbAttachment) => {
    FormDataRef.value?.resetFields()
    attachmentIds.value = [record.id] as number[]
    classify_visible.value = true
}

const handleCancelClassify = () => {
    FormData.value.category = undefined
}

const handleOkClassify = () => {
    if(EditLoading.value) {
        return
    }
    EditLoading.value = true
    FormData.value.id = attachmentIds.value
    UpdateAttachment(iPb.Admin.UpdateAttachmentRequest.create(FormData.value)).then((_result:iPb.Admin.IUpdateAttachmentResponse) => {
        EditLoading.value = false
        Message.success({
            content: "操作成功",
        })
        initList()
        classify_visible.value = false
    })
}

const initList = (page = 1, limit = 15) => {
    if(loading.value) {
        return
    }
    loading.value = true
    search.value.limit = limit
    search.value.page = page
    search.value.category = active.value
    ListAttachment(iPb.Admin.ListAttachmentRequest.create(search.value)).then((result:iPb.Admin.IListAttachmentResponse) => {
        let R = iPb.Admin.ListAttachmentResponse.create(result)
        tableData.value = R.data
        total.value = R.count
        loading.value = false
    })
}

const handleDelete = (id: number) => {
    if(EditLoading.value) {
        return
    }
    EditLoading.value = true
    DeleteAttachment(iPb.Admin.DeleteAdminRequest.create({
        id: id
    })).then((_result: iPb.Admin.IDeleteAdminResponse) => {
        EditLoading.value = false
        Message.success({
            content: "删除成功",
        })
        initList()
    })
}
const handlePagination = (e: { current: number | undefined; pageSize: number | undefined; }) => {
    initList(e.current, e.pageSize)
}

const columns:TableColumnsType = [
    {
        title: "附件地址",
        dataIndex: "file_url",
        ellipsis: true
    },
    {
        title: "附件分组",
        dataIndex: "category",
        ellipsis: true
    },
    {
        title: "附件名称",
        dataIndex: "original_name",
    },
    {
        title: "附件（大小 / 类型）",
        dataIndex: "file_size",
    },
    {
        title: "操作",
        dataIndex: "operate",
    }
]

onMounted(() => {
    let tabsData = store.Config.attachment_category
    TabsData.value = [
        {
            title: "全部",
            value: ""
        }
    ].concat(tabsData)
    active.value = TabsData.value[0].value
    initList()
})
</script>
